package com.dmj.sqldsl.builder;

import com.dmj.sqldsl.builder.column.ValueColumnBuilder;
import com.dmj.sqldsl.builder.column.type.ColumnLambda;
import com.dmj.sqldsl.builder.condition.ConditionsBuilder;
import com.dmj.sqldsl.builder.config.EntityConfig;
import com.dmj.sqldsl.builder.table.EntityBuilder;
import com.dmj.sqldsl.model.DslUpdate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class UpdateBuilder<T> {

  private final EntityBuilder entityBuilder;

  private final List<SetBuilder> setBuilders;


  private UpdateBuilder(EntityBuilder entityBuilder) {
    this.entityBuilder = entityBuilder;
    this.setBuilders = new ArrayList<>();
  }

  public static <T> UpdateBuilder<T> on(Class<T> entityClass) {
    return new UpdateBuilder<>(new EntityBuilder(entityClass));
  }

  public <R> UpdateBuilder<T> set(ColumnLambda<T, R> columnLambda, R value) {
    setBuilders.add(
        new SetBuilder(columnLambda.getColumnBuilder(), new ValueColumnBuilder<>(value)));
    return this;
  }

  public UpdateWhereBuilder<T> where(ConditionsBuilder conditionsBuilder) {
    return new UpdateWhereBuilder<>(this, conditionsBuilder);
  }

  protected DslUpdate toUpdate(EntityConfig config) {
    return DslUpdate.builder()
        .table(entityBuilder.buildTable(config))
        .sets(setBuilders.stream().map(x -> x.build(config)).collect(Collectors.toList()))
        .build();
  }
}
